package com.quan.mall.service.impl;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.quan.commons.core.bean.R;
import com.quan.commons.core.biz.support.MyBaseServiceImpl;
import com.quan.commons.core.utils.PageUtils;
import com.quan.mall.entity.*;
import com.quan.mall.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.quan.mall.commons.vo.FmsReportCommisionVo;
import com.quan.mall.mapper.FmsReportCommisionMapper;


@Slf4j
@Service
public class FmsReportCommisionServiceImpl extends MyBaseServiceImpl<FmsReportCommisionMapper, FmsReportCommision> implements FmsReportCommisionService {

    @Autowired
	private FmsReportCommisionMapper mapper;

    @Autowired
	private FmsMemberCashFlowService fmsMemberCashFlowService;

    @Autowired
    private UmsMemberService umsMemberService;

    @Autowired
    private OmsOrderService omsOrderService;

    @Autowired
    private WmsAgentInfoService wmsAgentInfoService;

	@Override
    public List<FmsReportCommisionVo> queryList(PageUtils pageUtils, FmsReportCommisionVo vo) {
        QueryWrapper<FmsReportCommision> queryWrapper = new QueryWrapper<FmsReportCommision>(vo);

        List<FmsReportCommision> list = super.list(pageUtils, queryWrapper);
        List<FmsReportCommisionVo> collect = list.stream().map(item -> {
            FmsReportCommisionVo bean = new FmsReportCommisionVo();
            BeanUtils.copyProperties(item, bean);
            return bean;
        }).collect(Collectors.toList());

        return collect;
    }

    @Override
    public PageUtils queryPage(PageUtils pageUtils, FmsReportCommisionVo vo) {
        QueryWrapper<FmsReportCommision> queryWrapper = new QueryWrapper<FmsReportCommision>(vo);

        if(StringUtils.isNotBlank(vo.getKeyword())) {
            queryWrapper.and(w -> {
                w.like("order_sn", vo.getKeyword())
                .or().like("member_name", vo.getKeyword())
                .or().like("agent_name", vo.getKeyword());
            });
        }

        // 订单时间选择->0:今天;1:昨天;2:最近7天;3:最近30天:4:本月;5本年
        if (null != vo.getDateAttrOrder()) {
            if (vo.getDateAttrOrder() == 0) {
                queryWrapper.apply("date_format(order_time, '%Y-%m-%d') >= {0}", LocalDate.now());
            } else if (vo.getDateAttrOrder() == 1) {
                queryWrapper.apply("date_format(order_time, '%Y-%m-%d') >= {0}", LocalDate.now().plusDays(-1));
            } else if (vo.getDateAttrOrder() == 2) {
                queryWrapper.apply("date_format(order_time, '%Y-%m-%d') >= {0} and date_format(order_time, '%Y-%m-%d') <= {1}", LocalDate.now().plusDays(-7), LocalDate.now());
            } else if (vo.getDateAttrOrder() == 3) {
                queryWrapper.apply("date_format(order_time, '%Y-%m-%d') >= {0} and date_format(order_time, '%Y-%m-%d') <= {1}", LocalDate.now().plusDays(-30), LocalDate.now());
            } else if (vo.getDateAttrOrder() == 4) {
                // 本月的第一天
                final LocalDate firstMonthDay = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
                // 本月的最后一天
                final LocalDate lastMonthDay = LocalDate.now().plusYears(1).with(TemporalAdjusters.firstDayOfMonth());
                queryWrapper.apply("date_format(order_time, '%Y-%m-%d') >= {0} and date_format(order_time, '%Y-%m-%d') <= {1}", firstMonthDay, lastMonthDay);
            } else if (vo.getDateAttrOrder() == 5) {
                // 今年的第一天
                final LocalDate firstYearDay = LocalDate.now().with(TemporalAdjusters.firstDayOfYear());
                // 今年的最后一天
                final LocalDate lastYearDay = LocalDate.now().plusYears(1).with(TemporalAdjusters.firstDayOfYear());
                queryWrapper.apply("date_format(order_time, '%Y-%m-%d') >= {0} and date_format(order_time, '%Y-%m-%d') <= {1}", firstYearDay, lastYearDay);
            }
        } else {
            // 订单日期范围
            if (StringUtils.isNotEmpty(vo.getDateRangeOrder())) {
                final String[] split = vo.getDateRangeOrder().split(",");
                String startDate = split[0];
                String endDate = split[1];
                queryWrapper.apply("date_format(order_time, '%Y-%m-%d') >= {0} and date_format(order_time, '%Y-%m-%d') <= {1}", startDate, endDate);
            }
        }

        // 记录时间选择->0:今天;1:昨天;2:最近7天;3:最近30天:4:本月;5本年
        if (null != vo.getDateAttrRecord()) {
            if (vo.getDateAttrRecord() == 0) {
                queryWrapper.apply("date_format(ctime, '%Y-%m-%d') >= {0}", LocalDate.now());
            } else if (vo.getDateAttrRecord() == 1) {
                queryWrapper.apply("date_format(ctime, '%Y-%m-%d') >= {0}", LocalDate.now().plusDays(-1));
            } else if (vo.getDateAttrRecord() == 2) {
                queryWrapper.apply("date_format(ctime, '%Y-%m-%d') >= {0} and date_format(ctime, '%Y-%m-%d') <= {1}", LocalDate.now().plusDays(-7), LocalDate.now());
            } else if (vo.getDateAttrRecord() == 3) {
                queryWrapper.apply("date_format(ctime, '%Y-%m-%d') >= {0} and date_format(ctime, '%Y-%m-%d') <= {1}", LocalDate.now().plusDays(-30), LocalDate.now());
            } else if (vo.getDateAttrRecord() == 4) {
                // 本月的第一天
                final LocalDate firstMonthDay = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth());
                // 本月的最后一天
                final LocalDate lastMonthDay = LocalDate.now().plusYears(1).with(TemporalAdjusters.firstDayOfMonth());
                queryWrapper.apply("date_format(ctime, '%Y-%m-%d') >= {0} and date_format(ctime, '%Y-%m-%d') <= {1}", firstMonthDay, lastMonthDay);
            } else if (vo.getDateAttrRecord() == 5) {
                // 今年的第一天
                final LocalDate firstYearDay = LocalDate.now().with(TemporalAdjusters.firstDayOfYear());
                // 今年的最后一天
                final LocalDate lastYearDay = LocalDate.now().plusYears(1).with(TemporalAdjusters.firstDayOfYear());
                queryWrapper.apply("date_format(ctime, '%Y-%m-%d') >= {0} and date_format(ctime, '%Y-%m-%d') <= {1}", firstYearDay, lastYearDay);
            }
        } else {
            // 记录日期范围
            if (StringUtils.isNotEmpty(vo.getDateRangeRecord())) {
                final String[] split = vo.getDateRangeRecord().split(",");
                String startDate = split[0];
                String endDate = split[1];
                queryWrapper.apply("date_format(ctime, '%Y-%m-%d') >= {0} and date_format(ctime, '%Y-%m-%d') <= {1}", startDate, endDate);
            }
        }

        final IPage<FmsReportCommision> page = super.selectPage(pageUtils, queryWrapper);

        PageUtils ps = new PageUtils(page);

        final List<FmsReportCommision> records = page.getRecords();

        final List<FmsReportCommision> collect = records.stream().map((item) -> {
            FmsReportCommisionVo bean = new FmsReportCommisionVo();
            BeanUtils.copyProperties(item, bean);
            return bean;
        }).collect(Collectors.toList());

        ps.setRecords(collect);
        return ps;
    }

    @Override
    public R expose(FmsReportCommisionVo vo) {

	    List<FmsMemberCashFlow> cashFlowList = this.fmsMemberCashFlowService.getCashFlowExpose();

	    // 根据订单号分组（因为一个订单号可能产生两条交易流水，1：业务分销提成，2：代理商分销提成）
        final Map<String, List<FmsMemberCashFlow>> collect = cashFlowList.stream().collect(Collectors.groupingBy(FmsMemberCashFlow::getSaleGoodsOrderSn));

        for (String orderSn : collect.keySet()) {
            log.info("订单号：{}", orderSn);

            // 订单
            final OmsOrder order = this.omsOrderService.getOrderByOrderSn(orderSn);

            final List<FmsMemberCashFlow> list = collect.get(orderSn);
            for (FmsMemberCashFlow flow : list) {
                log.info("会员：{}，订单号：{}，订单金额：{}", flow.getMemberName(), flow.getSaleGoodsOrderSn(), flow.getSaleGoodsOrderAmount());

                final UmsMember member = this.umsMemberService.getById(flow.getMemberId());

                FmsReportCommision fmsReportCommision = new FmsReportCommision();
                fmsReportCommision.setMemberCommission(BigDecimal.ZERO);
                fmsReportCommision.setAgentCommission(BigDecimal.ZERO);
                fmsReportCommision.setCompanyCommission(BigDecimal.ZERO);

                // 会员类型：1->游客，2->普通会员，3->VIP会员，4->业务代理;注：需与级别中的level同步，5->代理商
                if(member.getType() == 2 || member.getType() == 3 || member.getType() == 4) {
                    fmsReportCommision.setOpenId(member.getOpenid());
                    fmsReportCommision.setMemberId(member.getId());
                    fmsReportCommision.setMemberName(member.getNickname());
                    fmsReportCommision.setMemberCommission(flow.getTransactionAmount());
                    if(member.getType() == 4) {
                        // 会员标记：1->内部员工，2->外部分销
                        if(member.getMemberFlag() == 1) {
                            fmsReportCommision.setMemberFlag(1);
                        } else {
                            fmsReportCommision.setMemberFlag(2);
                        }
                    }

                }

                // 会员为代理商
                if(member.getType() == 5) {

                    if(null != order.getAgentId()) {
                        final WmsAgentInfo agentInfo = this.wmsAgentInfoService.getById(order.getAgentId());

                        // 标记为非业务代理（代理商）
                        fmsReportCommision.setMemberFlag(0);
                        fmsReportCommision.setAgentId(agentInfo.getId());
                        fmsReportCommision.setAgentName(agentInfo.getName());
                        fmsReportCommision.setAgentCommission(flow.getTransactionAmount());
                    }

                }


                fmsReportCommision.setOrderTime(order.getCtime());
                fmsReportCommision.setOrderSn(order.getOrderSn());
                fmsReportCommision.setOrderAmount(order.getPayAmount());

                // 总部分成 = 订单金额-会员分成-代理商分成
                fmsReportCommision.setCompanyCommission(order.getPayAmount().subtract(fmsReportCommision.getMemberCommission()).subtract(fmsReportCommision.getAgentCommission()));

                super.save(fmsReportCommision);

                // 已清算
                flow.setIsExpose(1);
                this.fmsMemberCashFlowService.updateById(flow);
            }
        }

        return R.ok();
    }
}